package com.snap.vseries.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.snap.vseries.Constants;
import com.snap.vseries.R;
import com.snap.vseries.base.BaseFragment;
import com.snap.vseries.bean.ExpInfo;
import com.snap.vseries.bean.TempBean;
import com.snap.vseries.chart.SimpleChartGestureListener;
import com.snap.vseries.chart.TimeFormatter;
import com.snap.vseries.chart.YAxisTempFormatter;
import com.snap.vseries.ui.ExpRunningActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 运行中温度曲线
 */
@SuppressLint("ValidFragment")
public class RunningTempFragment extends BaseFragment {

    private static final String TAG = "RunningTempFragment";
    private static final int MSG_GET_DATA = 99;
    private static final int MSG_RENDER_ON_CHART = 98;

    @BindView(R.id.chart)
    LineChart chart;
    @BindView(R.id.tec_temp_tv)
    TextView tecTempTv;
    @BindView(R.id.group_ll)
    LinearLayout tempTvLayout;

    private boolean renderOnChart = true;
    private List<TempBean> tempList;
    @SuppressLint("HandlerLeak")
    private Handler renderHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSG_GET_DATA) {
                render();
                sendEmptyMessageDelayed(MSG_GET_DATA, 1000);
            } else if (msg.what == MSG_RENDER_ON_CHART) {
                renderOnChart = true;
            }
        }
    };

    public RunningTempFragment(ExpInfo expInfo) {
        if (expInfo == null) {
            return;
        }
        this.tempList = expInfo.getTempData().get(0);
    }

    public RunningTempFragment() {

    }

    @Override
    protected int layoutResId() {
        return R.layout.fragment_running_temp;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        initChart();
    }

    @Override
    public void onDestroyView() {
        renderHandler.removeCallbacksAndMessages(null);
        super.onDestroyView();
    }

    private void initChart() {
        //图表整体设置
        chart.setDrawGridBackground(false);//背景颜色
        chart.getDescription().setEnabled(false);//图表的描述信息
        chart.getLegend().setEnabled(false);//图例
        chart.setDrawBorders(false);//图表外边框
        chart.setMaxVisibleValueCount(0);

        //左右的两根Y轴配置
        chart.getAxisRight().setEnabled(false);
        YAxis yAxis = chart.getAxisLeft();//左面的Y轴
        yAxis.setEnabled(true);//开启
        yAxis.setDrawAxisLine(true);//绘制轴线
        yAxis.setDrawGridLines(true);//绘制网格线
        yAxis.enableGridDashedLine(9f, 4f, 0);
        yAxis.setAxisLineColor(0xffe8e9ee);
        yAxis.setGridColor(0xffe8e9ee);
        yAxis.setTextColor(0xff8d909f);
        yAxis.setAxisMaximum(125 * 100);
        yAxis.setAxisMinimum(0);
        yAxis.setGranularity(10f);
        yAxis.setLabelCount(12);
        yAxis.setValueFormatter(new YAxisTempFormatter());

        //X轴配置
        XAxis xAxis = chart.getXAxis();
        xAxis.setEnabled(true);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置X轴位置在图表底部
        xAxis.setDrawAxisLine(false);
        xAxis.setDrawGridLines(true);
        xAxis.setGridColor(0xffe8e9ee);
        xAxis.setTextColor(0xff8d909f);
        xAxis.setGranularity(1f);
        xAxis.setValueFormatter(new TimeFormatter());

        //操作相关
        chart.getViewPortHandler().setMinMaxScaleX(1f, 20f);
        chart.getViewPortHandler().setMinMaxScaleY(1f, 20f);
        chart.setHighlightPerDragEnabled(false);
        chart.setHighlightPerTapEnabled(false);
        chart.setTouchEnabled(true);
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setPinchZoom(true);
        chart.setOnChartGestureListener(new SimpleChartGestureListener() {
            @Override
            public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
                renderOnChart = false;
                chart.setVisibleXRangeMaximum(Integer.MAX_VALUE);
                renderHandler.removeMessages(MSG_RENDER_ON_CHART);
            }

            @Override
            public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
                //最后一次操作10秒后，开始自动刷新
                renderHandler.sendEmptyMessageDelayed(MSG_RENDER_ON_CHART, 10 * 1000);
            }
        });

        //模块温度 init data()
        List<ILineDataSet> dataSets = new ArrayList<>();
        LineDataSet dataSet = new LineDataSet(new ArrayList<>(), 1 + "模块温度");
        dataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);//线的样式
        dataSet.setLineWidth(2f);//线宽
        dataSet.setDrawCircles(false);//是否画点
        dataSet.setDrawValues(false);//是否画值
        dataSet.setColor(ContextCompat.getColor(getContext(), R.color.primary_green));//线的颜色
        dataSets.add(dataSet);

        //环境温度
//        LineDataSet envDataSet = new LineDataSet(new ArrayList<>(), "环境温度");
//        envDataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
//        envDataSet.setLineWidth(2f);
//        envDataSet.setDrawCircles(false);
//        envDataSet.setDrawValues(false);
//        dataSet.setDrawFilled(true);
//        envDataSet.setColor(getContext().getColor(R.color.temp));
//        Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.fade_temp);
//        envDataSet.setFillDrawable(drawable);
//        dataSets.add(envDataSet);

        LineData lineData = new LineData(dataSets);
        chart.setData(lineData);
        chart.invalidate();

        if (((ExpRunningActivity) getContext()).expController != null) {
            if (((ExpRunningActivity) getContext()).expController.getExpState() == Constants.EXP_STATE_RUNNING) {
                renderHandler.obtainMessage(MSG_GET_DATA).sendToTarget();
            } else {
                render();
                tempTvLayout.setVisibility(View.GONE);
            }
        }
    }

    private void render() {
        LineData data = chart.getLineData();
        if (data == null) {
            return;
        }
        if (getActivity() != null) {
            if (((ExpRunningActivity) getActivity()).expController != null) {
                tempList = ((ExpRunningActivity) getActivity()).expController.getExpInfo().getTempData().get(0);
            }
        }
        //模块温度
        if (tempList != null) {
            ILineDataSet set = data.getDataSetByIndex(0);
            int showCount = set.getEntryCount();
            int dataCount = tempList.size();
            if (dataCount > showCount) {
                for (int j = showCount; j < dataCount; j++) {
                    set.addEntry(new Entry(tempList.get(j).getSec(), tempList.get(j).getTemperature()));
                }
                tecTempTv.setText(tempList.get(dataCount - 1).getTemperature() / 100f + "°C");
            }
        }
        if (renderOnChart) {
            data.notifyDataChanged();
            chart.notifyDataSetChanged();
            chart.setVisibleXRangeMaximum(300);
            chart.moveViewToX(data.getEntryCount());
            chart.fitScreen();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {
            renderHandler.removeMessages(MSG_GET_DATA);
        } else if (((ExpRunningActivity) getContext()).expController.getExpState() == Constants.EXP_STATE_RUNNING) {
            renderHandler.obtainMessage(MSG_GET_DATA).sendToTarget();
        } else {
            render();
            tempTvLayout.setVisibility(View.GONE);
        }
    }

    public void stopRender() {
        renderHandler.removeMessages(MSG_GET_DATA);
        tempTvLayout.setVisibility(View.GONE);
        render();
    }
}
